package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.model.vo.VideoScore;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RecommendVideoListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取日志消息，构造评分的数据保存到mongo数据库
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.log.video"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.video"
            )
    )
    public void video(String message){
        System.out.println("获取到日志消息="+message);
        //1、解析消息数据
        Map<String,String> map = JSON.parseObject(message, Map.class);
        //2、获取map中的数据
        String logTime = map.get("logTime");  //操作时间
        String type = map.get("type");        //操作类型
        String str = map.get("userId");       //用户ID
        Long userId = Long.valueOf(str);
        String busId = map.get("busId"); //业务id（动态id或者视频id）
        //3、构造score对象，存入Mongodb
        VideoScore score = new VideoScore();
        score.setUserId(userId);
        score.setVideoId(new ObjectId(busId));
        score.setDate(System.currentTimeMillis());
        score.setScore(getScore(type));
        mongoTemplate.save(score);
    }

    private static Double getScore(String type) {
        //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }
}
